package com.qf.lja.dao;

import com.qf.lja.enity.*;
import com.qf.lja.util.JDBCUtil;
import com.qf.lja.util.RandomUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class OrderDao {


    public List<Orders> findOrderList(Integer u_id) {
        String sql = "select * from buyr_address a join buyr_order o on a.`address_id` = o.`address_id`" +
                " where o.user_id = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet rs = jdbcUtil.query(sql, u_id);

        List<Orders> ordersList = new ArrayList<>();
        try {
            while (rs.next()) {
                Orders orders = new Orders();
                orders.setAddress(convertToAddress(rs));
                orders.setOrderId(rs.getString("order_id"));
                orders.setUserId(rs.getInt("user_id"));
                orders.setAddressId(rs.getInt("address_id"));
                orders.setTotalPrice(rs.getDouble("total_price"));
                orders.setPayMethod(rs.getString("pay_method"));
                orders.setLeaveComment(rs.getString("leave_comment"));
                orders.setOrderStatus(rs.getInt("order_status"));
                orders.setCreatedTime(rs.getDate("created_time"));
                orders.setUpdatedTime(rs.getDate("updated_time"));

                ordersList.add(orders);
            }
            return ordersList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    //查询一个order
    public Orders findOrderById(String orderId) {
        String sql = "select * from buyr_address a join buyr_order o on a.`address_id` = o.`address_id`" +
                " where o.order_id = ?";

        Orders orders = new Orders();
        JDBCUtil jdbcUtil = new JDBCUtil();
        ResultSet rs = jdbcUtil.query(sql, orderId);

        List<Item> items = new ArrayList<>();

        try {
            if (rs.next()) {
                ItemDao itemDao = new ItemDao();
                orders.setAddress(convertToAddress(rs));
                orders.setOrderId(rs.getString("order_id"));
                orders.setUserId(rs.getInt("user_id"));
                orders.setAddressId(rs.getInt("address_id"));
                orders.setTotalPrice(rs.getDouble("total_price"));
                orders.setPayMethod(rs.getString("pay_method"));
                orders.setLeaveComment(rs.getString("leave_comment"));
                orders.setOrderStatus(rs.getInt("order_status"));
                orders.setCreatedTime(rs.getDate("created_time"));
                orders.setUpdatedTime(rs.getDate("updated_time"));
                orders.setItems(itemDao.findItemByOrderId(orderId));
            }
            return orders;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Address convertToAddress(ResultSet rs) {
        try {
            Address address = new Address();
            address.setAddressId(rs.getInt("address_id"));
            address.setRecipients(rs.getString("recipients"));
            address.setPhone(rs.getString("phone"));
            address.setAddrName(rs.getString("addr_name"));
            address.setDefalutAddr(rs.getInt("defalut_addr"));
            return address;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String createorder(String a_id, String u_id, String sum) {
        String OrderId = RandomUtils.createOrderId();
//        orders.setOrderId(OrderId);
//        orders.setUserId();
//        orders.setAddressId();
//        orders.setTotalPrice();
        String sql = "insert into buyr_order(order_id,user_id,address_id," +
                "total_price,`pay_method`,leave_comment, order_status,created_time,updated_time) " +
                "values(?,?,?,?,?,?,?,CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP())";
        JDBCUtil jdbcUtil = new JDBCUtil();
        jdbcUtil.insert(sql, OrderId, Integer.parseInt(u_id), Integer.parseInt(a_id)
                , Double.parseDouble(sum), "支付宝", "暂无留言", 0);

        //查找购物车所有商品
        CartDao cartDao = new CartDao();
        List<Cart> carts = cartDao.findAllByUserId(Integer.parseInt(u_id));

        List<Item> items = new ArrayList<>();

        for (Cart cart : carts) {
            Item item = new Item();
            item.setO_id(OrderId);
            item.setP_id(cart.getProductId());
            item.setI_count(cart.getTotalPrice());
            item.setI_num(cart.getProductQuantity());
            item.setProduct(cart.getProduct());
            items.add(item);
        }

        ItemDao itemDao = new ItemDao();
        itemDao.addItem(items);

        //清空购物车
        cartDao.clearCart(Integer.parseInt(u_id));
        jdbcUtil.closeConnection();
        return OrderId;
    }

    public String Dpcreateorder(String u_id, Integer p_id) {
        AddrDao addrDao = new AddrDao();
        ProductDao productDao = new ProductDao();
        Product product = productDao.findByProductId(p_id);
        String OrderId = RandomUtils.createOrderId();
//        orders.setOrderId(OrderId);
//        orders.setUserId();
//        orders.setAddressId();
//        orders.setTotalPrice();
        String sql = "insert into buyr_order(order_id,user_id,address_id," +
                "total_price,`pay_method`,leave_comment, order_status,created_time,updated_time) " +
                "values(?,?,?,?,?,?,?,CURRENT_TIMESTAMP(),CURRENT_TIMESTAMP())";
        JDBCUtil jdbcUtil = new JDBCUtil();
        jdbcUtil.insert(sql, OrderId, Integer.parseInt(u_id),
                addrDao.getDefaultAddrId(Integer.parseInt(u_id))
                , Double.parseDouble(product.getPrice().toString()), "支付宝", "暂无留言", 0);

        //查找购物车所有商品
        CartDao cartDao = new CartDao();
        List<Cart> carts = cartDao.findAllByUserId(Integer.parseInt(u_id));
        List<Item> items = new ArrayList<>();
        Item item = new Item();
        item.setO_id(OrderId);
        item.setP_id(product.getProductId());
        item.setI_count(product.getPrice());
        item.setI_num(1);
        item.setProduct(product);
        items.add(item);

        ItemDao itemDao = new ItemDao();
        itemDao.addItem(items);

        //不需要清空购物车
//        //清空购物车
//        cartDao.clearCart(Integer.parseInt(u_id));
//        jdbcUtil.closeConnection();
        return OrderId;
    }

    public void updateOrderStatus(String orderId) {
        String sql = "update buyr_order set order_status = ? where order_id = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        jdbcUtil.update(sql, 1, orderId);
        jdbcUtil.closeConnection();
    }

    public void updateStock(String orderId) {
        Orders orders = findOrderById(orderId);
        List<Item> items = orders.getItems();
        for (Item item : items) {
            ProductDao productDao = new ProductDao();
            productDao.updateStock(item.getP_id(), item.getI_num());
        }
    }

    public List<Orders> findOrderByIdAndStatu(Integer userId, String statusFilter) {
        String sql = "select * from buyr_order where user_id = ? and order_status = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        try {
            ResultSet rs = jdbcUtil.query(sql, userId, statusFilter);
            List<Orders> orders = new ArrayList<>();
            while (rs.next()) {
                Orders order = convertToOrder(rs);
                orders.add(order);
            }
            return orders;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Orders convertToOrder(ResultSet rs) {
        try {
            Orders orders = new Orders();
            orders.setOrderId(rs.getString("order_id"));
            orders.setUserId(rs.getInt("user_id"));
            orders.setAddressId(rs.getInt("address_id"));
            orders.setPayMethod(rs.getString("pay_method"));
            orders.setTotalPrice(rs.getDouble("total_price"));
            orders.setOrderStatus(rs.getInt("order_status"));
            orders.setCreatedTime(rs.getDate("created_time"));
            orders.setUpdatedTime(rs.getDate("updated_time"));
            orders.setAddress(new AddrDao().findById(orders.getAddressId()));
            orders.setItems(new ItemDao().findByOrderId(orders.getOrderId()));
            return orders;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
